package ferp.android.tasks.local;

import android.content.Context;
import android.os.AsyncTask;
import ferp.android.managers.DeckManager;

/**
 * User: olegs
 * Date: 1/2/14 12:30 PM
 */
public class TaskDeckLoader extends AsyncTask<Void, Void, Void>
{
  public static interface Listener
  {
    void onDeckLoadStart(String deck);
    void onDeckLoadFinished(DeckManager dm, String deck);
  }

  public static void execute(Context context, Listener listener, String deck)
  {
    DeckManager dm = DeckManager.instance(context);

    if (instance == null && dm.isLoadRequired(context, deck))
    {
      dm.setReady(false);

      instance = new TaskDeckLoader(context, listener, dm, deck);
      instance.execute();
    }
    else
      done(listener, dm, deck);
  }

  @Override
  protected void onPreExecute()
  {
    listener.onDeckLoadStart(deck);
  }

  @Override
  protected Void doInBackground(Void... voids)
  {
    dm.load(context, deck);

    return null;
  }

  @Override
  protected void onPostExecute(Void aVoid)
  {
    dm.refresh();
    done(listener, dm, deck);

    instance = null;
  }

  private static TaskDeckLoader instance;

  private Context context;
  private Listener listener;
  private DeckManager dm;
  private String deck;

  private static void done(Listener listener, DeckManager dm, String deck)
  {
    dm.setReady(true);
    listener.onDeckLoadFinished(dm, deck);
  }

  private TaskDeckLoader(Context context, Listener listener, DeckManager dm, String deck)
  {
    this.context  = context;
    this.listener = listener;
    this.dm       = dm;
    this.deck     = deck;
  }

}
